package com.cyy.util

import cn.hutool.json.JSONUtil
import com.jfinal.kit.Kv
import java.util.HashMap

object U{

    /**
     * 将形如str的字符串转换成jfinal 的Kv
     * @param str {ret=[{name:111}, {name:王麻子1}, {name:1111}], title=address, cols=[name]}
     * @return Kv
     */
    fun str2Kv(str:String):Kv{
        val kv = str.replace("=", ":")
        val kv1 = Kv.create()
        JSONUtil.parseObj(kv).entries.forEach {
            kv1.set(it.key, it.value)
        }
        return kv1
    }
    /**
     * 使用 Map按key进行排序得到key=value的字符串
     * @param plain
     * @param eqaulsType K与V之间的拼接字符串 = 或者其他...
     * @param spliceType K-V与K-V之间的拼接字符串  & 或者|...
     * @return
     */
    fun strToMap(plain: String?, eqaulsType: String,
                 spliceType: String): Map<String, String>? {
        if (plain == null || plain.isEmpty()) {
            return null
        }

        val map = HashMap<String, String>()

        val split = plain.split(spliceType.toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
        for (kv in split) {
            if ("|" == kv) {
                continue
            }
            val kvArr = kv.split(eqaulsType.toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
            if (kvArr.size == 2) {
                map[kvArr[0]] = kvArr[1]
            } else {
                map[kvArr[0]] = ""
            }
        }

        return map
    }
}